using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace WPCoco.Particles
{
    public static class ParticleStore
    {
        const int MIN_CAPACITY = 300;
        const int MAX_CAPACITY = 5000;

        static ParticleStore()
        {
            EnsureCapacity(MIN_CAPACITY);
        }

        static List<LinkedListNode<Particle>> cache = new List<LinkedListNode<Particle>>(500);

        public static void EnsureCapacity(int capacity)
        {
            int dif = capacity - cache.Count;
            if (dif <= 0) return;
            dif = Math.Max(dif, 50);
            //LinkedListNode<Particle>[] nodes = new LinkedListNode<Particle>[dif];
            for (int i = 0; i < dif; i++)
                cache.Add(new LinkedListNode<Particle>(new Particle()));
                //nodes[i] = new LinkedListNode<Particle>(new Particle());
            //cache.AddRange(nodes);
        }

        public static LinkedListNode<Particle> ReuseOneNode() 
        {
            if (cache.Count == 0) return null;
            LinkedListNode<Particle> node = cache[cache.Count - 1];
            cache.RemoveAt(cache.Count - 1);
            return node;
        }

        public static void RestoreNode(LinkedListNode<Particle> node) 
        {
            if (cache.Count >= MAX_CAPACITY) return;
            cache.Add(node);
        }

        public static void PruneCache() 
        {
            if (cache.Count <= MIN_CAPACITY) return;
            cache.RemoveRange(MIN_CAPACITY, cache.Count - MIN_CAPACITY);
        }
    }
}
